package com.dayaokeji.rhythmschoolstudent.client.home.meeting;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.seat.GenerateSeatPlaceActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.data.bean.SignTypeBean;
import com.dayaokeji.rhythmschoolstudent.event.UpdateMeetingEvent;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.DateUtils;
import com.dayaokeji.rhythmschoolstudent.utils.InputUtils;
import com.dayaokeji.rhythmschoolstudent.utils.SeatUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.MeetingApi;
import com.dayaokeji.server_api.domain.CreateMeeting;
import com.dayaokeji.server_api.domain.MeetingInfo;
import com.dayaokeji.server_api.domain.UserInfo;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 创建会议
 */
public class CreateMeetingActivity extends BaseActivity {

    public static final int CHOOSE_MEETING_ROOM_REQUEST_CODE = 10001;
    public static final int CHOOSE_PARTICIPANTS_REQUEST_CODE = 10002;


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_meeting_time)
    TextView tvMeetingTime;
    @BindView(R.id.et_meeting_subject)
    EditText etMeetingSubject;
    @BindView(R.id.tv_meeting_room)
    TextView tvMeetingRoom;
    @BindView(R.id.tv_sign_in_way)
    TextView tvSignInWay;
    @BindView(R.id.tv_join_member)
    TextView tvJoinMember;
    private Set<UserInfo> participantsArrayList;
    private MeetingInfo meetingInfo;

    private static final MeetingApi meetingApi = ApiUtils.getApi(MeetingApi.class);
    private Call<ServerResponse<Void>> createCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_meeting);
        setSupportActionBar(toolbar);

        init();
    }

    private void init() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.create_meeting,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_save_meeting:
                createMeetingValidate();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick({
            R.id.ll_choose_time,
            R.id.ll_choose_room,
            R.id.ll_choose_sign_type,
            R.id.ll_choose_participants, // 与会者
            R.id.btn_check_the_seating
    })
    public void onClick(View view) {
        AndroidUtils.hideSoftInput(getWindow());
        switch (view.getId()) {
            case R.id.ll_choose_time:
                showDatePickerDialog();
                break;
            case R.id.ll_choose_room:
                startActivityForResult(new Intent(CreateMeetingActivity.this, ChooseMeetingRoomActivity.class), CHOOSE_MEETING_ROOM_REQUEST_CODE);
                break;
            case R.id.ll_choose_sign_type:
                showSignTypeDialog();
                break;
            case R.id.ll_choose_participants:
                Intent intent = new Intent(CreateMeetingActivity.this, ChooseParticipantsActivity.class);
                intent.putExtra(ChooseParticipantsActivity.EXTRA_CHOOSER_PARTICIPANTS, (Serializable) participantsArrayList);
                startActivityForResult(intent,CHOOSE_PARTICIPANTS_REQUEST_CODE);
                break;
            case R.id.btn_check_the_seating:
                generateSeatPlace();
                break;
        }
    }

    /**
     * 创建会议时验证
     */
    private void createMeetingValidate() {
        if (InputUtils.validateInput(etMeetingSubject,"请输入会议主题") &&
                InputUtils.validateInput(tvMeetingTime,"请选择会议时间") &&
                InputUtils.validateInput(tvMeetingRoom,"请选择会议室") &&
                InputUtils.validateInput(tvSignInWay,"请选择签到方式")) {
            if (participantsArrayList != null && participantsArrayList.size() > 0) {
                createMeeting();
            }else{
                ToastUtils.warning("请选择参加人员");
            }
        }
    }

    /**
     * 创建会议
     */
    private void createMeeting() {
        CreateMeeting createMeeting = new CreateMeeting();
        createMeeting.setName(etMeetingSubject.getText().toString().trim());
        createMeeting.setTime(tvMeetingTime.getText().toString());
        createMeeting.setTeacherId(UserUtils.getUserInfo().getId());
        createMeeting.setTotal(participantsArrayList.size());
        createMeeting.setType(1);
        createMeeting.setPictureId("-1");
        createMeeting.setCreateTime(getCreateTime());
        createMeeting.setRoomId((int) tvMeetingRoom.getTag());
        createMeeting.setSignType((int) tvSignInWay.getTag());
        createMeeting.setUserSeatList(SeatUtils.getUserSeatList(meetingInfo.getSeat(),getUserIds()));
        createMeeting.setAddress(tvMeetingRoom.getText().toString());


        createCall = meetingApi.create(createMeeting);
        createCall.enqueue(new ServerCallback<Void>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    EventBus.getDefault().post(new UpdateMeetingEvent());
                    ToastUtils.success("创建会议成功");
                    ActivityStackManager.finish();
                }
            }
        });
    }


    private String getCreateTime() {
        StringBuilder createTime = new StringBuilder();
        createTime.append(Calendar.getInstance().get(Calendar.YEAR));
        createTime.append("-");
        createTime.append(Calendar.getInstance().get(Calendar.MONTH));
        createTime.append("-");
        createTime.append(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        return createTime.toString();
    }


    /**
     * 显示时间选择器
     */
    private void showDatePickerDialog() {
        final TimePickerView pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View view) {
                tvMeetingTime.setText(DateUtils.format(date,DateUtils.FORMAT_DATETIME_SHORT2));
            }
        })
        .setType(new boolean[]{true, true, true, true, true, false})
                .setTitleText("选择会议时间")
                .build();
        pickerView.setDate(Calendar.getInstance());
        pickerView.show();
    }

    /**
     * 选择签到类型
     */
    private void showSignTypeDialog(){
        final List<SignTypeBean> signTypeList = new ArrayList<>();
        signTypeList.add(new SignTypeBean(1,"路由签到"));
        final OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int i, int i1, int i2, View view) {
                tvSignInWay.setText(signTypeList.get(i).getName());
                tvSignInWay.setTag(signTypeList.get(i).getType());
            }
        })
                .setTitleText("选择签到方式")
                .build();
        optionsPickerView.setPicker(signTypeList);
        optionsPickerView.show();
    }

    /**
     * 生成会议排座
     */
    private void generateSeatPlace() {
        if (meetingInfo == null) {
            ToastUtils.info("请先选择会议室");
            return;
        }
        if (participantsArrayList == null || participantsArrayList.size() == 0) {
            ToastUtils.info("请选择参与人员");
            return;
        }
        try{
            Intent intent = new Intent(CreateMeetingActivity.this, GenerateSeatPlaceActivity.class);
            intent.putExtra(GenerateSeatPlaceActivity.EXTRA_TITLE,meetingInfo.getName());
            intent.putExtra(GenerateSeatPlaceActivity.EXTRA_SEAT_STR,meetingInfo.getSeat());
            intent.putExtra(GenerateSeatPlaceActivity.EXTRA_USER_SEATS, (Serializable) SeatUtils.generateUsersMap(meetingInfo.getSeat(), getUserIds()));
            startActivity(intent);
        }catch (Exception e) {
            ToastUtils.warning("排座时发生错误");
            e.printStackTrace();
        }
    }

    /**
     * 得到用户id
     * @return
     */
    private List<Integer> getUserIds() {
        List<Integer> userIds = new ArrayList<>();
        if (participantsArrayList != null) {
            for (UserInfo userInfo : participantsArrayList) {
                userIds.add(Integer.valueOf(userInfo.getId()));
            }

            return userIds;
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case CHOOSE_MEETING_ROOM_REQUEST_CODE:
                    if (data != null) {
                        meetingInfo = (MeetingInfo) data.getSerializableExtra(ChooseMeetingRoomListFragment.EXTRA_MEETING_INFO);
                        if (meetingInfo != null) {
                            tvMeetingRoom.setText(meetingInfo.getName());
                            tvMeetingRoom.setTag(meetingInfo.getId());
                        }
                    }
                    break;
                case CHOOSE_PARTICIPANTS_REQUEST_CODE:
                    participantsArrayList = ((Set<UserInfo>) data.getSerializableExtra(ChooseParticipantsActivity.EXTRA_CHOOSER_PARTICIPANTS));
                    tvJoinMember.setText("已选择"+String.valueOf(participantsArrayList == null? 0 : participantsArrayList.size())+"人");
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (createCall != null) {
            createCall.cancel();
        }
        super.onDestroy();
    }
}
